<template>
    <div class="wrap">
        <dv-loading v-if="loading"></dv-loading>
        <template v-else>
            <div class="wrap-map">
                <el-bmap class="map" ref="bgmap" :map-style-v2="darkStyle" :center="center" :zoom="zoom" :min-zoom="10" :max-zoom="19" :events="events">
                    <template v-for="(marker, index) in projectList">
                        <el-bmap-marker :icon="marker.icon" :position="[marker.longitude,marker.latitude]" :title="marker.projName" :events="markerEvents" :vid="index" ref="marks"></el-bmap-marker>
                        <el-bmap-label :content="marker.projName" :visible="labelVisible" :label-style="labelStyle" :offset="['-90px','35px']" :position="[marker.longitude,marker.latitude]"></el-bmap-label>

                    </template>
                </el-bmap>

                <div class="detail-box" v-drag v-if="infoShow">
                    <div class="detail-hd">
                        <h5>项目简介</h5>
                        <span @click="detail(marker.projCode)">查看详情 >></span>
                    </div>
                    <div class="detail-con">
                        <el-image class="detai-img" :lazy='true' :src="marker.thumbnail" fit="cover"></el-image>
                        <h4><el-tag size="small" :type="marker.state == 1 ? 'info' : marker.state == 4 ? 'success' : marker.state == 3 ? 'danger' : ''">{{marker.state == 1 ? '准备' : marker.state == 2 ? '在建' : marker.state == 4 ? '竣工' : '停工'}}</el-tag> {{marker.projName}}</h4>
                        <div class="detail-bd">
                            <p>项目地址：{{marker.address}}</p>
                            <p>建设单位：{{marker.buildUnitName}}</p>
                            <p>设计单位：{{marker.designUnitName}}</p>
                            <p>施工单位：{{marker.mainContractorName}}</p>
                            <p>监理单位：{{marker.supervisorUnitName}}</p>
                        </div>
                        <div class="close">
                            <i class="el-icon-circle-close" @click="clearPro"></i>
                        </div>
                        
                    </div>
                </div>
                <!-- 项目搜索框 -->
                <div class="search">
                    <el-select v-model="projCode" style="width: 260px;" clearable filterable @clear="clearPro" placeholder="请输入项目名称选择" @change="showPro">
                        <el-option
                        v-for="item in projectList"
                        :key="item.projCode"
                        :label="item.projName"
                        :value="item.projCode">
                        </el-option>
                    </el-select>
                </div>
            </div>
            <!-- header -->
            <div class="wrap-header">
                <div class="logo-box">
                    <img src="../../assets/images/logo.png" />
                    <h3>智慧工地企业级监管平台</h3>
                </div>
                <div class="logo-center">
                    <div class="item" v-for="(item,index) in nav" :key="index" @mouseover="mouseOver(index)" :class="index == activeMenu ? 'active itemHover' : ''" @click="handleChangeNav(index)">
                        <i :class="item.icon"></i>
                        <span>{{item.name}} </span>
                    </div>
                </div>
                <div class="timer">
                <i class="iconfont icon-shizhongfill"></i>
                <div class="time-date">
                    <p>{{nowtime}}</p>
                    <span>{{nowdate}}</span>
                </div>
                <img src="../../assets/images/outlogin.png" @click="outLogin">
                </div>
            </div>
            <!-- 左侧边栏 -->
            <!-- <div class="wrap-nav">
                <div class="item" v-for="(item,index) in nav" :key="index" :class="index == activeMenu ? 'active' : ''" @click="handleChangeNav(index)">
                    <i :class="item.icon"></i>
                    <span>{{item.name}} </span>
                </div>
            </div> -->
            <div class="wrap-right">
                <div v-if="!activeComponent" class="slide-left" @click="slideLeft">
                    <i class="el-icon-d-arrow-left"></i>
                </div>
                <transition name="slide-fade">
                    <component :is="activeComponent" :theme="theme">
                        <div v-if="activeComponent" class="slide-right" @click="slideRight">
                            <i class="el-icon-d-arrow-right"></i>
                        </div>
                    </component>
                </transition>
            </div>
            <div class="wrap-bottom" :style="{right:activeComponent ? '470px' : '20px'}" :class="isBottomHide ? 'slide-down' : ''">
                <div class="slide-down" v-if="!isBottomHide" @click="isBottomHide = true">
                    <i class="el-icon-d-arrow-left"></i>
                </div>
                <div class="slide-up" v-else @click="isBottomHide = false">
                    <i class="el-icon-d-arrow-right"></i>
                </div>
               <div class="warning-wrap light">
                <div class="datav-box">
                    <div class="datav-title">
                        <h4>预警信息</h4>
                        <div class="select-box">
                            <el-select v-model="query.alarm_type" placeholder="请选择预警类型" size="mini" style="margin-right: 15px;" clearable @change="getWarningList">
                                <el-option v-for="item in warningType" :key="item.id" :value="item.alarm_key" :label="item.alarm_value"></el-option>
                            </el-select>
                            <el-date-picker
                            v-model="warningDate"
                            type="daterange"
                            size="mini"
                            range-separator="至"
                            start-placeholder="开始日期"
                            @change="changeDate"
                            end-placeholder="结束日期">
                            </el-date-picker>
                        </div>
                    </div>
                    <div class="datav-con">
                        <el-table ref="table" :data="tableData" height="192" style="width: 100%;overflow-y: hidden;" >
                            <el-table-column prop="index" label="序号" width="80"></el-table-column>
                            <el-table-column prop="projetname" label="项目名称" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="type" label="预警类型" show-overflow-tooltip width="140"></el-table-column>
                            <el-table-column prop="exceptioninfo" label="预警描述" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="alarmtime" label="预警时间" show-overflow-tooltip width="160"></el-table-column>
                        </el-table>
                    </div>
                </div>
               </div>
            </div>
        </template>
    </div>
</template>

<script>
import mapStyle from './components/mapStyle2'
import { mapGetters ,mapMutations} from "vuex";
import moment from 'moment'
export default {
    components:{
        overview:() => import('./components/overview.vue'),
        quality:() => import('./components/quality.vue'),
        device:() => import('./components/device.vue'),
        ai:() => import('./components/ai.vue'),
        materials:() => import('./components/materials.vue'),
        safety: () => import('./components/safety.vue'),
        labour: () => import('./components/labour.vue'),
        warning:() => import('./components/warning.vue'),
    },
    computed:{
        nowtime(){
            return moment(this.nowDate).format('HH:mm:ss')
        },
        nowweek(){
            let weeks = ['日','一','二','三','四','五','六']
            let e = moment(this.nowDate).format('e')
            return '星期' + weeks[e]
        },
        nowdate(){
            return moment(this.nowDate).format('YYYY/MM/DD')
        },
        ...mapGetters(["projects",'userinfo'])
    },
    data(){
        return{
            //配色
            theme:'light',
            //地图
            zoom:12,
            center: [113.306438,23.15817],
            map: null,
            nowDate:new Date(),
            events:{
                init: (o) => {
                    this.map = o;
                },
                zoomend:(e) => {
                    this.labelVisible = !(this.map.zoomLevel < 13.5)
                },
                // dragstart:()=>{
                //     this.infoShow = false
                // },
            },
            markerEvents:{
                click:(e) => {
                    let vid = e.currentTarget._config.vid
                    this.handleMarkerClick(vid)
                }
            },
            darkStyle:mapStyle,
            labelStyle:{
                'color':"rgba(0,0,0,0.8)",
                'border':'none',
                'font-size':'12px',
                'background':'none',
                'text-align':'center',
                'width':'200px',
                'line-height':'18px',
                'word-break':'break-all',
                'white-space':'pre-wrap'
            },
            labelVisible:false,
            //menu
            nav:[
                {name:'首页总览',icon:'el-icon-data-analysis',component:'overview',en:'Overview'},
                // {name:'进度管理',icon:'icon-jindutiao'},
                // {name:'质量管理',icon:'icon-zhiliang3',component:'quality',en:'Quality Management'},
                // {name:'安全管理',icon:'icon-yujing',component:'safety',en:'Safety Management'},
                {name:'劳务管理',icon:'el-icon-s-custom',component:'labour',en:'Labor Management'},
                {name:'智能设备',icon:'el-icon-connection',component:'device',en:'Smart Devices'},
                {name:'视频AI',icon:'el-icon-video-camera',component:'ai',en:'Video&AI'},
                //{name:'物资管理',icon:'icon-ziyuan213',component:'materials',en:'Material Management'},
            ],
            activeMenu:0,
            activeComponent:'overview',
            //项目
            projectList:[],
            infoShow:false,
            marker:"",
            projectids:"",
            loading:false,
            projCode:"",
            isBottomHide:false,
            query:{
                projectid:'',
                alarm_type:'',
                start:"",
                end:""
            },
            warningType:[],
            warningDate:[],
            tableData:[],
            timer:null
        }
    },
    created() {
        // if(getUrlSearch('tab') >= 0){
        //     this.activeMenu = getUrlSearch('tab') || 0 
        //     this.activeComponent = this.nav[this.activeMenu].component || 'overview'
        // }
        this.loading = false
        //获取用户项目
        let projectids = this.userinfo.projectCodes
        this.projectids = projectids.toString()
        this.SET_PROJECT(this.projectids)
        if(projectids.length == 1){
            this.$router.push({ path: '/datap',
                    query:{
                        id:this.projectids
                    }
                }
            )
        }
        if(projectids.length == 0){
            this.$alert('当前项目暂无智慧工地平台！', '提示', {
                confirmButtonText: '关闭页面',
                callback: action => {
                    window.open("about:blank", "_top").close()
                }
            });
            return
        }
        this.getProjectList()
        this.getWarningType()
        this.getWarningList()
        this.loading = false
    },
    mounted(){
        setInterval(()=>{
            this.nowDate = new Date()
        },1000)
    },
    beforeDestroy() {
        this.timer && clearInterval(this.timer);
    },
    methods: {
        //切换导航
        handleChangeNav(idx){
            this.activeMenu = idx
            this.activeComponent = this.nav[idx].component
        },
        mouseOver(idx){
            this.activeMenu = idx
        },
        slideRight(){
            this.activeComponent = ''
        },
        slideLeft(){
            this.activeComponent = this.nav[this.activeMenu].component
        },
        downImage(e){
            console.log(e)
        },
        //全部项目列表
        getProjectList(){
            this.$api.getProjectList({projectid:this.projectids}).then(res => {
                if(res.code == 0){
                    res.data.map(item => {
                        item.detailshow = false
                        if(item.state && item.state == 1) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/yellow-light.png',size:[23,30]}
                        if(item.state && item.state == 2) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/blue-light.png',size:[23,30]}
                        if(item.state && item.state == 4) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/green-light.png',size:[23,30]}
                        if(item.state && item.state == 3) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/red-light.png',size:[23,30]}
                        item.image = item.bgImage ? JSON.parse(item.bgImage)[0] : ''
                        item.thumbnail = ""
                    })
                    this.projectList = res.data
                }
            })
        },
        handleMarkerClick(idx){
            this.marker = this.projectList[idx]
            this.center = [this.marker.longitude,this.marker.latitude]
            this.infoShow = true
            
            this.projectList.map((item,index) => {
                if(item.state && item.state == 1) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/yellow-light.png',size:[23,30]}
                if(item.state && item.state == 2) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/blue-light.png',size:[23,30]}
                if(item.state && item.state == 4) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/green-light.png',size:[23,30]}
                if(item.state && item.state == 3) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/red-light.png',size:[23,30]}
            })
            let imglist = JSON.parse(this.marker.bgImage)
            if(imglist.length>0){
                this.marker.thumbnail = imglist[0].url
                // this.$api.downImage(this.marker.image.id).then(res => {
                //     if(!res.code) this.marker.thumbnail = res
                // })
            }
            setTimeout(() => {
                this.$set(this.projectList[idx],'icon',{ url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/active.png',size:[23,30]})
            },100)
        },
        detail(id){
            let routeUrl = this.$router.resolve({
                path: '/datap',
                query:{
                    id:id
                }
            });
            window.open(routeUrl.href, '_blank');
        },
        showPro(){
            let idx = this.projectList.findIndex(item => {
                return item.projCode == this.projCode
            })
            this.handleMarkerClick(idx)
        },
        clearPro(){
            this.projCode = ""
            this.infoShow = false
            this.projectList.map((item) => {
                if(item.state && item.state == 1) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/yellow-light.png',size:[23,30]}
                if(item.state && item.state == 2) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/blue-light.png',size:[23,30]}
                if(item.state && item.state == 4) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/green-light.png',size:[23,30]}
                if(item.state && item.state == 3) item.icon = { url:'https://iotx.oss-cn-beijing.aliyuncs.com/platform-gz/image/red-light.png',size:[23,30]}
            })
        },
        changeDate(e){
            this.query.start = e ? moment(e[0]).format("YYYY-MM-DD") : ''
            this.query.end = e ? moment(e[1]).format("YYYY-MM-DD") : ''
            this.getWarningList()
        },
        getWarningType(){
            this.$datav.getWarningType().then(res => {
                this.warningType = res.data
            })
        },
        getWarningList(){
            this.query.projectid = this.projectids
            this.timer && clearInterval(this.timer);
            
            this.$datav.getWarningList(this.query).then(res => {
                let arr = []
                res.data.content.map((item,index) => {
                    item.index = index + 1
                    arr.push(item)
                })                    
                this.tableData = arr.length > 3 ? arr.concat(arr) : arr
                const table = this.$refs.table;
                // 拿到表格中承载数据的div元素
                const divData = table.bodyWrapper
                divData.scrollTop = 0
                this.$nextTick(() => {
                    this.infinitScroll()
                })
                
            })
        },
        infinitScroll() {
            let _this = this
            // 拿到表格挂载后的真实DOM
            const table = this.$refs.table;
            // 拿到表格中承载数据的div元素
            const divData = table.bodyWrapper
            divData.onmouseover = function () {
                _this.timer && clearInterval(_this.timer);
            }; //鼠标移入，停止滚动
            divData.onmouseout = function () {
                start()
            }; //鼠标移出，继续滚动
            
            // 拿到元素后，对元素进行定时增加距离顶部距离，实现滚动效果(此配置为每100毫秒移动1像素)
            function start() {
                // 数据少于表格高度停止滚动
                if (divData.clientHeight >= divData.scrollHeight){
                    return;
                    }
                    _this.timer = setInterval(() => {
                    // 元素自增距离顶部1像素
                    divData.scrollTop += 1
                    // 判断元素是否滚动到底部(可视高度+距离顶部=整个高度)
                    if (divData.clientHeight + divData.scrollTop == divData.scrollHeight) {
                    // 重置table距离顶部距离
                    divData.scrollTop = divData.scrollTop - divData.scrollHeight/2
                    }
                }, 50)
            }
            start()
        },
        outLogin(){
         this.$store.dispatch('user/logout').then((res) => {
            this.$router.push({
              path:"/login"
            })
          }).catch((err)=>{console.log(err)})    
        },
        ...mapMutations('user',['SET_PROJECT'])
    },
}
function getUrlSearch(name) {
  // 未传参，返回空
  if (!name) return null;
  // 查询参数：先通过search取值，如果取不到就通过hash来取
  var after = window.location.search;
  after = after.substr(1) || window.location.hash.split('?')[1];
  // 地址栏URL没有查询参数，返回空
  if (!after) return null;
  // 如果查询参数中没有"name"，返回空
  if (after.indexOf(name) === -1) return null;
 
  var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
  // 当地址栏参数存在中文时，需要解码，不然会乱码
  var r = decodeURI(after).match(reg);
  // 如果url中"name"没有值，返回空
  if (!r) return null;
 
  return r[2];
}
</script>

<style lang="scss" scoped>
.wrap{
    width: 100vw;
    height: 100%;
    overflow: hidden;
    position: relative;
}
.map{
    width: 100vw;
    height: 100vh;
}
::v-deep .anchorBL {
  display: none;
}
.wrap-map{
    position: relative;
    .search{
        position: absolute;
        top: 82px;
        left: 20px;
        z-index: 9999;
    }
}

.wrap-header{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    padding: 0 24px;
    min-width: 1366px;
    height: 60px;
    z-index: 100;
    display: flex;
    justify-content: space-between;
    align-items: center;
    // background-image: linear-gradient(270deg,#1e92ff,#1d42ab);
    background: linear-gradient(90deg, #56A1FF 0%, #3C91FB 100%);
    .logo-box{
        display: flex;
        align-items: center;
        img {
          width: 32px;
          height: 32px;
        }
        h3{
            margin: 0 0 0 8px;
            font-size: 22px;
            line-height: 1.2;
            font-weight: normal;
            color: #fff;
        }
    }
    .logo-center{
        width: 60%;
        height: 100%;
        display: flex;
        justify-content: space-around;
        align-items: center;
        .item{
            width: 150px;
            height:100%;
            line-height: 60px;
            color: #fff;
            font-size: 16px;
            text-align: center;
            cursor: pointer;
                i{
                    padding-right: 9px;
                }
        }
    }
    .itemHover{
        animation: logoboxMenu 1s forwards;
    }
    .timer{
        display: flex;
        align-items: center;
        color: #fff;
        i{
            font-size: 30px;
            margin-right: 8px;
        }
        .time-date{
            display: flex;
            flex-direction: column;
            justify-content: center;
            p{
                margin:0;
                font-size: 18px;
            }
            span{
                font-size: 14px;
            }
        }
        img{
            width: 25px;
            height: 26px;
            margin-left: 55px;
            cursor: pointer;
        }
    }
}
.wrap-nav{
    position: absolute;
    background: rgba(255,255,255,0.8);
    left: 0;
    width: 208px;
    top: 60px;
    bottom: 0;
    overflow-y: auto;
    padding-top: 6px;
    z-index: 999;
    border-right: 1px solid #e9e9e9;
    .item{
        display: flex;
        align-items: center;
        cursor: pointer;
        flex: 1;
        padding-left: 24px;
        height: 40px;
        margin: 4px 0;
        i{
            font-size: 14px;
            margin-right: 10px;
            color: rgba(0,0,0,.65);
        }
        span {
          font-size: 14px;
          font-weight: normal;
          color: rgba(0,0,0,.65);
        }
        &.active{
            background: #e6f7ff;
            border-right: 3px solid #1890ff;
            i{
                color: #1890ff;
            }
            span {
              color: #1890ff;
            }
        }
    }
}
.wrap-bottom{
    position: fixed;
    transition: all .3s ease;
    bottom: 0;
    left: 20px;
    right: 470px;
    height: 247px;
    z-index: 100;
    .warning-wrap{
        background: #fff;
        width: 100%;
        height: 100%;
        padding:15px 20px;
        border-radius: 4px;
    }
    .slide-up,.slide-down{
        position: absolute;
        cursor: pointer;
        transition: all .3s ease;
        width: 40px;
        height: 40px;
        display: flex;
        justify-content: center;
        align-items: center;
        background: #1E7DE9;
        box-shadow: 0px 3px 6px 1px rgba(0,0,0,0.1600);
        border-radius: 0px 0px 4px 4px;
        font-size: 16px;
        color: #fff;
        top: 0;
        right: 10px;
        z-index: 99;
        i{
            transform: rotate(-90deg);
        }
    }
    .slide-up{
        border-radius: 4px 4px 0px 0px;
        top: -40px;
    }
    &.slide-down,&.slide-up{
        transform: translateY(100%);
    }
}
.slide-fade-enter-active {
  transition: all .2s ease;
}
.slide-fade-leave-active {
  transition: all .2s cubic-bezier(1.0, 0.5, 0.8, 1.0);
}
.slide-fade-enter, .slide-fade-leave-to {
  transform: translateX(100%);
  opacity: 0;
}


.slide-right,.slide-left{
  position: fixed;
  right:450px;
  top:70px;
  z-index: 100;
  cursor: pointer;
  transition: all .3s ease;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #1E7DE9;
  box-shadow: 0px 3px 6px 1px rgba(0,0,0,0.1600);
  border-radius: 4px 0px 0px 4px;
  font-size: 16px;
  color: #fff;
}
.slide-left{
  right:0;
}

.detail-box{
    width: 340px;
    height: 400px;
    background-size: cover;
    position: absolute;
    z-index: 9999;
    left: calc(50% - 350px);
    top: calc(50% - 200px);
    .detail-hd{
        display: flex;
        justify-content: space-between;
        align-items: center;
        color: rgba(255,255,255,0.85);
        background: #008AFF;
        border-radius: 12px 12px 0px 0px;
        height: 48px;
        padding: 0 20px;
        h5{
            margin: 0;
            font-size: 18px;
            font-weight: normal;
        }
        span{
            font-size: 14px;
            color: #CFD7FF;
            cursor: pointer;
        }
    }
    .detail-con{
        background: #fff;
        border-radius: 0 0 12px 12px;
        padding: 20px;
    }
    .detai-img{
        width: 100%;
        height: 130px;
        margin: 0 0 12px;
    }
    h4{
        font-weight: normal;
        font-size: 16px;
        color: rgba(0,0,0,0.85);
        margin: 0;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis; 
    }
    .detail-bd{
        color: rgba(0,0,0,0.85);
        p{
            font-size: 14px;
            margin: 12px 0;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis; 
        }
    }
    .close{
        font-size: 30px;
        color: #ddd;
        margin: 0 auto;
        text-align: center;
        i{
            cursor: pointer;
        }
    }
}
.datav-box{
    .datav-title{
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-right: 50px;
        h4{
            margin-bottom: 0;
        }
    }
}
::v-deep .el-table--scrollable-y .el-table__body-wrapper{
    overflow-y: hidden !important;
}

@keyframes logoboxMenu {
       0% {
           background: #0088ff00;
       }
       100% {
            background: rgba(255,255,255,0.24);
       }
   }
</style>
